//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.ManagementStudioControls.RegistryManagerModule
{
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Research.ScientificWorkflow.ManagementStudioModels;
    using System.Windows.Input;

    /// <summary>
    /// Interaction logic for AssemblyCatalogueLeftPane.xaml
    /// </summary>
    public partial class AssemblyCatalogueLeftPane : UserControl
    {
        public AssemblyCatalogueLeftPane()
        {
            InitializeComponent();
        }

        /// <summary>
        /// The selected item changed event on the treeview.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The event arguments.</param>
        private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            (this.DataContext as AssemblyCatalogueLeftPanePresenter).ItemSelectedCommand.Execute(e.NewValue as BaseRegMgrModel);
        }

        /// <summary>
        /// Event handler for the PreviewMouseDown event on the category treeview. This event is needed
        /// because the selection changed event does not fire when alternating between 2 controls.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The event arguments.</param>
        private void OnGridPreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            AssemblyCatalogueLeftPanePresenter presenter = this.DataContext as AssemblyCatalogueLeftPanePresenter;
            if (!presenter.IsSelected && assemblyTreeview.SelectedItem != null)
            {
                Grid selectedGrid = sender as Grid;
                if (selectedGrid != null)
                {
                    BaseRegMgrModel model = selectedGrid.DataContext as BaseRegMgrModel;

                    // If the mousedown happens on the currently selected item then fire the selected command.
                    if (assemblyTreeview.SelectedItem.Equals(model))
                    {
                        presenter.ItemSelectedCommand.Execute(model);
                    }
                }
            }
        }
    }
}
